package com.b2c.erp.controller;

import com.alibaba.fastjson.JSON;
import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.ContactEntity;
import com.b2c.entity.erp.InvoiceEntity;
import com.b2c.entity.erp.InvoiceInfoEntity;
import com.b2c.entity.erp.enums.ContactTypeEnum;
import com.b2c.entity.erp.enums.InvoiceBillStatusEnum;
import com.b2c.entity.erp.enums.InvoiceBillTypeEnum;
import com.b2c.entity.erp.enums.InvoiceTransTypeEnum;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.entity.enums.IsDeleteEnum;
import com.b2c.repository.utils.OrderNumberUtils;
import com.b2c.interfaces.wms.ContactService;
import com.b2c.interfaces.wms.ErpGoodsStockLogsService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.wms.InvoiceService;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.enums.erp.EnumGoodsStockLogSourceType;
import com.b2c.entity.enums.erp.EnumGoodsStockLogType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;


/**
 * @program: mall
 * @description: 采购退货管理
 * @author: Mr.Qi
 * @create: 2020-02-18 14:46
 **/

@Controller
@RequestMapping("/purchase")
public class PurchaseCancelController {
    @Autowired
    private InvoiceService invoiceService;
    @Autowired
    private ErpUserActionLogService logService;
    
    @Autowired
    private ContactService contactService;
    @Autowired
    private ErpGoodsStockLogsService goodsStockLogsService;
    Logger log = LoggerFactory.getLogger(PurchaseCancelController.class);
    /**
     * 采购退货单list
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_cancel_list", method = RequestMethod.GET)
    public String purchaseCancelList(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        String billNo = request.getParameter("billNo");
        model.addAttribute("billNo", billNo);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        String status = Optional.ofNullable(request.getParameter("status")).orElse("-1");

        String transType = request.getParameter("transType");
        InvoiceTransTypeEnum typeEnum = null;
        if(StringUtils.hasText(transType)){
            typeEnum = InvoiceTransTypeEnum.valueOf(transType);
        }
        Integer contactId = null;
        if(StringUtils.hasText(request.getParameter("contactId"))){
            contactId = Integer.parseInt(request.getParameter("contactId"));
        }

        
        PagingResponse<InvoiceEntity> result = invoiceService.getPurchaseCancelList(pageIndex, pageSize, typeEnum, billNo, Integer.parseInt(status),contactId);
        model.addAttribute("list", result.getList());
        model.addAttribute("totalSize", result.getTotalSize());

        //获取供应商
        List<ContactEntity> contacts = contactService.getList(ContactTypeEnum.Supplier);
        model.addAttribute("contacts", contacts);


        model.addAttribute("view", "cgthd");
        model.addAttribute("pView", "cg");
        model.addAttribute("ejcd", "出库");
        return "purchase_cancel_list";
    }


    /**
     * 退货单详情
     *
     * @param model
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_cancel_detail", method = RequestMethod.GET)
    public String purchaseInDetail(Model model, @RequestParam Long id, HttpServletRequest request) {
        var invoice = invoiceService.getInvoiceById(id);
        model.addAttribute("invoice", invoice);
        model.addAttribute("outId", id);
        var list = invoiceService.getErpInvoiceInfoByIid(id);
        model.addAttribute("list", list);
        try {
            model.addAttribute("msg", StringUtils.isEmpty(request.getParameter("msg")) ? "" : URLDecoder.decode(request.getParameter("msg"),"utf-8"));
        }catch (Exception e){
        }
        model.addAttribute("view", "cgthd");
        model.addAttribute("pView", "cg");
        return "purchase_cancel_detail";
    }

    /***
     * 采购退货
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_cancel", method = RequestMethod.GET)
    public String purchaseCancel(Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("trueName");
        model.addAttribute("userName", userName);
        model.addAttribute("time", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        log.info("访问新增采购退货页面：{userName:"+userName+"}");

        //生成单据编号
        String billNo = "RET" + OrderNumberUtils.getOrderIdByTime();
        model.addAttribute("billNo", billNo);

        model.addAttribute("invoiceId", 0);

        //获取供应商
        List<ContactEntity> contacts = contactService.getList(ContactTypeEnum.Supplier);
        model.addAttribute("contacts", contacts);

//        model.addAttribute("view", "cgth");
        model.addAttribute("pView", "cg");
        model.addAttribute("view", "cgthd");
        model.addAttribute("flag", "cgth");
        return "purchase_cancel";
    }


    /**
     * 添加退货单POST
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_cancel", method = RequestMethod.POST)
    public String addPurchaseCancel(Model model, HttpServletRequest request) {

        log.info("新增采购退货-提交：{userName:"+DataConfigObject.getInstance().getLoginUserName()+"}");
        /***表单信息***/
//        Long supplierId = 0l;
        Long supplierId = Long.parseLong(request.getParameter("supplierId"));
        String billNo = request.getParameter("billNo");
        String billDate = request.getParameter("billDate");
        Long invoiceId = Long.parseLong(request.getParameter("invoiceId"));
        String srcOrderId = request.getParameter("srcOrderId");
        if(invoiceId!=null && invoiceId.longValue() >0) srcOrderId=invoiceId.toString();

        String transType =request.getParameter("transType");
        String transTypeName = "";
        if(StringUtils.isEmpty(transType)){
            transType = InvoiceTransTypeEnum.PUR_RETURN.getIndex();
            transTypeName =InvoiceTransTypeEnum.PUR_RETURN.getName();
        }else{
            transTypeName=InvoiceTransTypeEnum.valueOf(transType).getName();
        }

        var invoice = invoiceService.getInvoiceById(invoiceId);

        Double invoiceDisRate = 0d;//优惠率
        Double invoiceDisAmount = 0d; //优惠金额
        Double invoiceAmount = 0d;//优惠后金额
        Double rpAmount = 0d;//本次付款
        Double arrears = 0d;//本次欠款

        /***要计算的内容***/
        Double totalAmount = 0.0;//购货总金额（商品价格*数量之和）
        Long totalQuantity = 0l;//总数量(商品数量之和）
        Double totalDiscount = 0.0;//总折扣（计算商品折扣和单据折扣之和）


        /***商品信息****/
        String[] specNumber = request.getParameterValues("specNumber");//规格编码组合
        String[] goodsNumber = request.getParameterValues("goodsNumber");//商品编码组合
        String[] goodsId = request.getParameterValues("goodsId");//商品id组合
        String[] specId = request.getParameterValues("specId");//商品规格id组合

        String[] quantity = request.getParameterValues("quantity");//数量组合
        String[] amount = request.getParameterValues("amount");
        String[] note = request.getParameterValues("note");//备注

        List<InvoiceInfoEntity> invoiceInfo = new ArrayList<>();
        if (specNumber != null && specNumber.length > 0) {
            //循环组合商品信息
            for (int i = 0; i < specNumber.length; i++) {
                InvoiceInfoEntity info = new InvoiceInfoEntity();
                if (StringUtils.isEmpty(specNumber[i]) == false) {
                    info.setSpecNumber(specNumber[i]);
                    info.setGoodsNumber(goodsNumber[i]);
                    if (goodsId.length > i) info.setGoodsId(Integer.valueOf(goodsId[i]));
                    if (specId.length > i) info.setSpecId(Integer.valueOf(specId[i]));
                    if (goodsNumber.length > i) info.setGoodsNumber(goodsNumber[i]);
                    if (quantity.length > i) info.setQuantity(Long.valueOf(quantity[i]));
                    info.setPrice(Double.valueOf(0d));
                    info.setDisRate(Double.valueOf(0d));
                    info.setDisAmount(Double.valueOf(0d));
                    // info.setAmount(Double.valueOf(0d));
                    info.setAmount(Double.valueOf(amount[i]));
                    
                    if (note.length > i) info.setDescription(note[i]);
                    
                    if (info.getPrice() != null && info.getQuantity() != null) {
                        totalQuantity += info.getQuantity();
                        // totalAmount += info.getPrice() * info.getQuantity();
                        totalAmount += Double.valueOf(amount[i]);
                        invoiceAmount += Double.valueOf(amount[i]);
                    }
                    if (info.getDisAmount() != null) totalDiscount += info.getDisAmount();
                    invoiceInfo.add(info);
                }
            }
        }
        if (invoiceDisAmount != null) totalDiscount += invoiceDisAmount;

        if (invoiceInfo == null || invoiceInfo.size() == 0) return "redirect:/purchase/purchase_cancel";

        InvoiceEntity invoiceEntity = new InvoiceEntity();
        invoiceEntity.setContactId(supplierId);
        invoiceEntity.setBillNo(billNo);
        invoiceEntity.setBillDate(billDate);
        invoiceEntity.setUserId(DataConfigObject.getInstance().getLoginUserId());
        invoiceEntity.setUserName(DataConfigObject.getInstance().getLoginUserName());
        invoiceEntity.setTransType(transType);
        invoiceEntity.setTransTypeName(transTypeName);
        invoiceEntity.setTotalAmount(totalAmount);
        invoiceEntity.setDisRate(invoiceDisRate);
        invoiceEntity.setDisAmount(invoiceDisAmount);
        invoiceEntity.setAmount(invoiceAmount);
        invoiceEntity.setTotalDiscount(totalDiscount);
        invoiceEntity.setTotalQuantity(totalQuantity);
        invoiceEntity.setRpAmount(rpAmount);

        invoiceEntity.setSrcOrderId(srcOrderId);//采购单id
        invoiceEntity.setSrcOrderNo(invoice == null ? "" : invoice.getBillNo());//采购单编号

        invoiceEntity.setArrears(arrears);
        invoiceEntity.setBillType(InvoiceBillTypeEnum.PUR_RETURN.getIndex());
        invoiceEntity.setBillStatus(InvoiceBillStatusEnum.WaitAudit.getIndex());
        invoiceEntity.setIsDelete(IsDeleteEnum.Normal.getIndex());
        invoiceEntity.setCreateTime(System.currentTimeMillis() / 1000);

        log.info("新增采购退货-提交"+ JSON.toJSONString(invoiceInfo));
        invoiceService.purchaseFormSubmit(invoiceEntity, invoiceInfo);
        //添加系统日志
        logService.addUserAction(DataConfigObject.getInstance().getLoginUserId(), EnumUserActionType.Add, "/purchase/purchase_cancel", "采购退货 , 编号 : " + billNo + ",日期 : " + new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()), "成功");
        return "redirect:/purchase/purchase_cancel_list";
    }

    /**
     * 退货商品出库
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_good_stock_out", method = RequestMethod.POST)
    public String purchaseInDetail(Model model, HttpServletRequest request) throws Exception {

        HttpSession session = request.getSession();

        Integer invoceId = Integer.parseInt(request.getParameter("StockInCheckoutId"));
        String[] outIds = request.getParameterValues("outItemId");
        String[] locationIds = request.getParameterValues("locationId");
        String[] numbers = request.getParameterValues("quantity");
        log.info("采购退货出库POST：{userName:"+DataConfigObject.getInstance().getLoginUserName()+"}");
        log.info("采购退货出库POST{invoceId:"+invoceId+",outIds:"+JSON.toJSONString(outIds)+",locationIds:"+JSON.toJSONString(locationIds)+",numbers:"+JSON.toJSONString(numbers)+"}");

        var resultVo = invoiceService.purchaseGoodOut(invoceId, outIds, locationIds, numbers, DataConfigObject.getInstance().getLoginUserId(), DataConfigObject.getInstance().getLoginUserName());

        if (resultVo.getCode() == 0)
            return "redirect:/purchase/purchase_cancel_list";
        else
            return "redirect:/purchase/purchase_cancel_detail?id=" + invoceId + "&msg=" + URLEncoder.encode(resultVo.getMsg(),"utf-8");

    }
    /**
     * 退货日志
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_cancel_stock_out_logs", method = RequestMethod.GET)
    public String purchaseOutLogs(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (StringUtils.isEmpty(request.getParameter("page")) == false) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }
        var result = goodsStockLogsService.getListByTypeAndSource(EnumGoodsStockLogType.OUT, EnumGoodsStockLogSourceType.PUR_RETURN, pageIndex, pageSize);
        //添加系统日志
        logService.addUserAction(Integer.parseInt(request.getSession().getAttribute("userId").toString()), EnumUserActionType.Query, "/purchase/purchase_cancel_stock_out_logs", "采购退货记录 , 日期 : " + new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()), "成功");
        model.addAttribute("list", result.getList());
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("view", "cgth");
        model.addAttribute("pView", "cg");
        model.addAttribute("flag", "cgthjl");
        return "purchase_cancel_stock_out_logs";
    }

    /***
     * 退货打印详情
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_cancel_print_detail", method = RequestMethod.GET)
    public String purchasePutDetail(Model model, HttpServletRequest request, @RequestParam Long id) {
        var detail = invoiceService.getDetailById(id);
        model.addAttribute("detail", detail);
        return "purchase_cancel_print_detail";
    }


}
